package com.example.mobilechannel;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

public class ConnectServer {

	private String host = "";
    private int port = 0;
    private Socket socket = null;
    private BufferedReader in = null;
    private PrintWriter out = null;

	public ConnectServer(String iHost, int iPort) throws IOException {
		host = iHost;
		port = iPort;
		//connect();
	}
	
	public void setHost(String iHost, int iPort) {
		host = iHost;
		port = iPort;
	}
	
	public String getHostAddr() {
		return host;
	}
	
	public int getPort(){
		return port;
	}
	
	public boolean connect() throws IOException {
		socket = new Socket(host, port);
		in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); 
		
		return true;
	}
	
	public String read() throws IOException {
		// TODO Auto-generated method stub
    	while(true) {
    		if (socket.isConnected()) {
    			if (!socket.isInputShutdown()) {
    				return in.readLine();
    			}
    		}
    	}
	}
	
	public boolean write(String buff) throws IOException {
		if (socket.isConnected()) {
			if(!"".equals(buff)) {
				if (!socket.isOutputShutdown()) {
					out.println(buff);
				}
			}
			else {
				return false;
			}
		}
		
		return true;
	}
	
	public boolean close() throws IOException {
		in.close();
		out.close();
		socket.close();
		return true;
	}
	
}
